<script setup>
import { ref, onMounted, computed } from 'vue';
import { useDocumentStore } from "@/stores/documentStore.js";
import DocumentDetail from "@/views/legal/DocumentDetail.vue";
import DocumentTemplate from "@/views/legal/DocumentTemplate.vue";
import DocumentSign from "@/views/legal/DocumentSign.vue";

import { ElMessageBox, ElMessage } from 'element-plus'

const documentStore = useDocumentStore();
const documentDetailRef = ref(null);
const documentTemplateRef = ref(null);
const documentSignRef = ref(null);
const showLaws = ref(false); // 将showLaws定义为响应式变量

// 初始化加载文档列表
onMounted(() => {
  documentStore.getDocumentList();
});

// 处理分页变化
const handleCurrentChange = (page) => {
  documentStore.handlePageChange(page);
};

// 查看文档详情
const handleDetail = (docId) => {
  documentDetailRef.value.show(docId);
};

// 生成新文档
const handleGenerate = () => {
  ElMessageBox.prompt('请输入案件ID', '生成新文档', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[a-zA-Z0-9]+$/,
    inputErrorMessage: '案件ID格式不正确'
  }).then(({ value }) => {
    documentStore.generateDocument(value).then(() => {
      ElMessage.success('文档生成成功');
    });
  }).catch(() => {
    ElMessage.info('取消生成');
  });
};

// 打开模板管理对话框
const handleTemplate = () => {
  documentTemplateRef.value.show();
};

// 打开签名对话框
const handleSign = (docId) => {
  documentSignRef.value.show(docId);
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString();
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'FINALIZED': '已定稿',
    'SIGNED': '已签名'
  };
  return statusMap[status] || status;
};

// 搜索文档
const handleSearch = () => {
  documentStore.pageInfo.page = 1; // 重置为第一页
  documentStore.getDocumentList();
};

// 重置搜索条件
const handleReset = () => {
  documentStore.resetQueryParams();
  documentStore.getDocumentList();
};

// 导出文档
const handleExport = (docId, format) => {
  documentStore.exportDocument(docId, format).then(() => {
    ElMessage.success('导出任务已开始');
  });
};

// 获取相关法律条款
const handleGetLaws = (docId) => {
  documentStore.getRelatedLaws(docId).then(() => {
    showLaws.value = true;
    ElMessage.success('法律条款已加载');
  });
};
</script>

<template>
  <div class="document-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="documentStore.queryParams" class="search-form">
        <el-form-item label="案件ID">
          <el-input v-model="documentStore.queryParams.caseId" placeholder="案件ID" clearable />
        </el-form-item>

        <el-form-item label="文书标题">
          <el-input v-model="documentStore.queryParams.title" placeholder="文书标题" clearable />
        </el-form-item>

        <el-form-item label="文书状态">
          <el-select v-model="documentStore.queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="DRAFT" />
            <el-option label="已定稿" value="FINALIZED" />
            <el-option label="已签名" value="SIGNED" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
              v-model="documentStore.queryParams.startTime"
              type="datetime"
              placeholder="开始时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span class="time-separator">至</span>
          <el-date-picker
              v-model="documentStore.queryParams.endTime"
              type="datetime"
              placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="operation-buttons">
        <el-button type="primary" @click="handleGenerate">生成新文档</el-button>
        <el-button type="info" @click="handleTemplate">模板管理</el-button>
      </div>
    </div>

    <!-- 文档表格 -->
    <el-table :data="documentStore.documentList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="caseId" label="案件ID" width="120" />
      <el-table-column prop="documentTitle" label="文书标题" width="200" />

      <el-table-column label="文书状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 'SIGNED' ? 'success' : row.status === 'DRAFT' ? 'warning' : ''">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="签名状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.signStatus === 'SIGNED' ? 'success' : 'info'">
            {{ row.signStatus === 'SIGNED' ? '已签名' : '未签名' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="版本号" width="100">
        <template #default="{ row }">
          <el-tag>v{{ row.currentVersion }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="最后编辑" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.lastEditTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleDetail(row.id)">详情</el-button>
          <el-button type="success" size="small" @click="handleGetLaws(row.id)">法律条款</el-button>
          <el-button type="warning" size="small" @click="handleSign(row.id)">签名</el-button>
          <el-dropdown>
            <el-button type="info" size="small">
              导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleExport(row.id, 'pdf')">导出PDF</el-dropdown-item>
                <el-dropdown-item @click="handleExport(row.id, 'word')">导出Word</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="documentStore.pageInfo.page"
          v-model:page-size="documentStore.pageInfo.size"
          :total="documentStore.pageInfo.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 法律条款展示区域 -->
    <el-dialog v-model="showLaws" title="相关法律条款" width="60%">
      <el-table :data="documentStore.relatedLaws" border>
        <el-table-column prop="lawName" label="法律名称" width="180" />
        <el-table-column prop="article" label="条款" width="120" />
        <el-table-column prop="clause" label="项" width="80" />
        <el-table-column prop="content" label="内容" />
      </el-table>
    </el-dialog>

    <!-- 文档详情对话框 -->
    <DocumentDetail ref="documentDetailRef" />

    <!-- 模板管理对话框 -->
    <DocumentTemplate ref="documentTemplateRef" />

    <!-- 签名对话框 -->
    <DocumentSign ref="documentSignRef" />
  </div>
</template>

<style scoped>
.document-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.time-separator {
  margin: 0 10px;
  color: #606266;
}

.operation-buttons {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>